<script setup>
import api from './api'
import { createName, $auth } from "@/utils"
import { to } from "@/utils/action"
import { ElMessage, ElMessageBox } from "element-plus"

const props = defineProps({
  url: { type: String, default: '' },
  // 导出枚举值【研发导出配置-->导出枚举管理-->导出值】
  name: { type: String, default: '' },
  // 当前api 主键 ： 一般为id
  mainKey: { type: String, default: '' },
  tableRef: { type: Object, default: () => ({}) },
  auth: { type: String, default: '' },
  task: Boolean,
})

const { url, name, task, mainKey } = props
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const fields = ref([])
const templates = ref([])
const config_id = ref(0)
const config_name = ref('')

const emit = defineEmits(['close', 'success'])

const query = async (del) => {
  const res = await api.getConfig({ home_system: 1, tag_name: name })
  const { config_id: id, config_name: cname, export_field, templates: tmps } = res.data
  config_id.value = id
  config_name.value = cname
  if (!del) {
    fields.value = export_field
    form.value.name = ''
  }
  templates.value = tmps
}

// 打开弹窗
const open = async () => {
  if (!load.value) {
    load.value = true
    await 1
  }
  await query()
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const handle = () => {
  if (task) {
    open()
    return
  }
  loadings.handle = true
  const condition = { [mainKey + 's']: props.tableRef.$table.getCheckboxRecords().map(d => d[mainKey]), ...props.tableRef.getQueryForm() }
  api.export(url, condition).then(blob => {
    ElMessage.success('导出成功，开始下载')
    props.tableRef.$table.saveFile({ filename: createName(name), type: 'xlsx', content: blob })
  }).finally(() => {
    loadings.handle = false
  })
}

const prevRow = (index) => {
  const row = fields.value.splice(index, 1)[0]
  fields.value.splice(index - 1, 0, row)
  fields.value = [...fields.value]
}

const nextRow = (index) => {
  const row = fields.value.splice(index, 1)[0]
  fields.value.splice(index + 1, 0, row)
  fields.value = [...fields.value]
}

const table = ref()
const expt = (tpl_id, rowIndex = '') => {
  const selection = table?.value.getCheckboxRecords()
  if (!selection.length && !tpl_id) {
    ElMessage.error('请先选择字段')
    return
  }
  loadings['expt' + rowIndex] = true
  const condition = { [mainKey + 's']: props.tableRef.$table.getCheckboxRecords().map(d => d[mainKey]), ...props.tableRef.getQueryForm() }
  api.taskExport({
    module: 'purchase', title: name, config_id: config_id.value, tpl_id, condition, fields: selection.map(d => d.field_key)
  }).then(res => {
    ElMessage.success('导出成功')
  }).finally(() => {
    loadings['expt' + rowIndex] = false
  })
}

// 添加模板
const addTamplate = () => {
  if (!form.value.name) {
    ElMessage.error('模板名称不能为空')
    return
  }
  const selection = table?.value.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.error('请先选择字段')
    return
  }
  loadings.add = true
  api.addTamplate({
    name: form.value.name, config_id: config_id.value, fields: selection.map(d => d.field_key)
  }).then(res => {
    form.value.name = ''
    query()
    ElMessage.success('保存成功')
  }).finally(() => {
    loadings.add = false
  })
}

// 删除模板
const delelteTamplate = (row, rowIndex) => {
  ElMessageBox.confirm('是否确认删除模板？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(() => {
      loadings['delete' + rowIndex] = true
      api.deleteTamplate(row.tpl_id).then(res => {
        query(true)
        ElMessage.success('删除成功')
      }).finally(() => {
        loadings['delete' + rowIndex] = false
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消操作', })
    })
}

// 选择模板
const check = async (row) => {
  await table?.value.clearCheckboxRow()
  const rows = fields.value.filter(d => row.fields.includes(d.field_key))
  table?.value.setCheckboxRow(rows, true)
}

defineExpose({ open })
</script>

<template>
  <template v-if="$auth(auth)">
    <el-button :loading="loadings.handle" icon="Upload" v-bind="$attrs" @click="handle">
      <slot>导出</slot>
    </el-button>
    <el-dialog v-if="load" :close-on-click-modal="false" title="导出中心" v-model="visible" append-to-body width="1000px"
      @close="handleClose">
      <template #header>
        <span class="el-dialog__title">导出中心</span>
        <span v-if="config_name"> - {{ config_name }}</span>
      </template>
      <div class="mt-1 mb-2">字段列表</div>
      <div class="grid grid-cols-2 gap-x-3">
        <vxe-table ref="table" :data="fields" height="auto">
          <vxe-column type="checkbox" width="40"></vxe-column>
          <vxe-column type="seq" width="60">
            <template #header>序号</template>
          </vxe-column>
          <vxe-column title="字段" field="field_name" min-width="160"></vxe-column>
          <vxe-column title="排序" width="140">
            <template #default="{ rowIndex }">
              <el-button link type="primary" @click="prevRow(rowIndex)">上移</el-button>
              <el-button link type="primary" @click="nextRow(rowIndex)">下移</el-button>
            </template>
          </vxe-column>
        </vxe-table>
        <div class="flex flex-col gap-2">
          <div class="flex items-center justify-between gap-x-2 mb-1">
            <el-button icon="upload" type="primary" class="col-span-3" :loading="loadings.expt"
              @click="expt()">导出</el-button>
            <div class="flex items-center flex-nowrap col-span-4">
              <el-icon style="font-size: 16px;">
                <Warning />
              </el-icon>
              <div class="whitespace-nowrap">导出结果在 <el-link type="primary"
                  @click="(visible = false) || to('/user/profile')">个人中心</el-link> 查看
              </div>
            </div>
          </div>
          <VGroup>
            <el-input v-model="form.name" placeholder="请输入" class="w-full" />
            <el-button type="primary" :loading="loadings.add" plain @click="addTamplate">保存模板</el-button>
          </VGroup>
          <vxe-table :data="templates">
            <vxe-column title="名称" field="name">
              <template #default="{ row }">
                <el-button link type="primary" @click="check(row)">{{ row.name }}</el-button>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="140">
              <template #default="{ row, rowIndex }">
                <el-button link type="primary" :loading="loadings['expt' + rowIndex]"
                  @click="expt(row.tpl_id, rowIndex)">导出</el-button>
                <el-button link type="danger" :loading="loadings['delete' + rowIndex]"
                  @click="delelteTamplate(row, rowIndex)">删除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="close">关 闭</el-button>
      </template>
    </el-dialog>
  </template>
</template>